<?php
namespace Admin\Controller;

use Think\Controller;

class MypublicController extends Controller
{
    //该控制内的方法不受权限限制
    public function __construct()
    {
        parent::__construct();
        if (empty($_SESSION['id']) || empty($_POST)) {
            if(empty($_FILES)){
                MycommonController::ajax('1002','参数有误','error');
            }
        }
    }

    /**
     * 获取该商户下面的所有出借人
     */
    public function get_lender(){
        $shop_idenfier=$_SESSION['shop_identifier'];
        $list=M('lender','','XYC')->WHERE(['shop_idenfier'=>$shop_idenfier,'is_delete'=>'1'])->FIELD("id,name")->SELECT();
        if(!empty($list)){
            MycommonController::ajax('1001',$list);
        }else{
            MycommonController::ajax('1002','暂未发现出借人');
        }
    }

    /**
     * 获取借款人详细信息
     */
    public function get_borrow_user_msg(){
        $shop_idenfier=$_SESSION['shop_identifier'];
        $param=I('param');
        $msg=M('user','','XYC')->WHERE(['shop_identifier'=>$shop_idenfier,'_string'=>"mobile='$param' or identity_num='$param'",'is_delete'=>'1'])->FIND();
        if(!empty($msg)){
            MycommonController::ajax('1001',$msg);
        }else{
            MycommonController::ajax('1002','未发现该用户信息');
        }
    }

    /**
     * 获取凭证详情
     */
    public function get_certificate_msg(){
        $orderno=I('orderno');
        $msg=D('Certificate')->WHERE(['numbering'=>$orderno])->FIND();
        if(!empty($msg)){
            $msg['loan_time']=date('Y-m-d',$msg['loan_time']);
            $msg['repayment_time']=date('Y-m-d',$msg['repayment_time']);
            MycommonController::ajax('1001',$msg);
        }else{
            MycommonController::ajax('1002','系统错误，请重新登录');
        }
    }

    /**
     * 获取续期信息
     */
    public function get_certificate_period(){
        $orderno=I('numbering');
        $msg=D('CertificatePeriod')->WHERE(['numbering'=>$orderno])->ORDER("id desc")->SELECT();
        if($msg!==false){
            $certificate_msg=D('Certificate')->WHERE(['numbering'=>$orderno])->FIND();
            //$check为1表示可以续借，已逾期、已续期、已打款都可以续借
            in_array($certificate_msg['status'],['2','3','4','9'])?$check='1':$check='2';
            $pre_repayment_time=$certificate_msg['repayment_time'];;
            if(!empty($msg)){
                foreach($msg as $k=>$v){
                    if($k=='0'){
                        $pre_repayment_time=$v['period_time'];
                    }
                    $msg[$k]['repayment_time']=date('Y-m-d',$v['repayment_time']);
                    $msg[$k]['period_time']=date('Y-m-d',$v['period_time']);
                    switch($msg[$k]['status']){
                        case '1':
                            $msg[$k]['status']='未确认';
                            break;
                        case '2':
                            $msg[$k]['status']='已确认';
                            break;
                        case '3':
                            $msg[$k]['status']='已取消';
                            break;
                    }
                }
            }else{
                $msg='';
            }
            $this->ajaxReturn([
                'code'=>'1001',
                'result'=>$msg,
                'repayment_time'=>date('Y-m-d',$pre_repayment_time),
                'check'=>$check
            ]);
//            MycommonController::ajax('1001',$msg);
        }else{
            MycommonController::ajax('1002','系统错误');
        }
    }

    /**
     * 获取角色列表
     */
    public function get_role()
    {
        $info = M('merchant_role', '', 'XYC');
        if (!empty($_POST)) {
            $list = $info->WHERE(['status' => '1'])->FIELD('id,rolename')->SELECT();
            MycommonController::ajax('1001',$list);
        } else {
            MycommonController::ajax('1002','获取失败','error');
        }
    }

    /**
     * 触发复制事件
     */
    public function copy(){
        $admin_event_db=M('adm_event','','USER');
        $mobile=I('mobile');
        if(!empty(I('mark'))){
            $data['content']='详情页面里复制用户'.$mobile.'手机号';
        }else{
            $data['content']='复制用户'.$mobile.'手机号';
        }
        $data['ctime']=time();
        $data['admin_name']=$_SESSION['name'];
        $data['login_ip']=getIP();
        $data['mobile']=$mobile;
        $data['cert_status']=M('user','','USER_R')->WHERE(['mobile'=>$mobile])->getField('cert_status');
        $admin_event_db->add($data);
        MycommonController::ajax('1001','成功');
    }

    /**
     * 触发复制事件
     */
    public function copy_all(){
        add_control_log($_SESSION['shop_identifier'],$_SESSION['account'],I('content'),'1');
        MycommonController::ajax('1001','成功');
    }

    /**
     *单图片上传
     */
    public function uploadimg(){
        if(!empty($_FILES)){
            $custom_name='';
            $type=I('type');
            if(!empty($type)){
                switch($type){
                    case '1':
                        $custom_name='';
                        break;
                    case '2':
                        $custom_name='@2x';
                        break;
                    case '3':
                        $custom_name='@3x';
                        break;
                }
            }
            MycommonController::uploadimg('uploadimg',$custom_name);
        }
    }

    /**
     * 编辑器图片上传
     */
    public function editor_upload(){
        MycommonController::editor_upload('fileDataFileName');
    }

    /**
     * 多图片上传
     */
    public function many_uploadimg(){
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }


        if ( !empty($_REQUEST[ 'debug' ]) ) {
            $random = rand(0, intval($_REQUEST[ 'debug' ]) );
            if ( $random === 0 ) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }

// header("HTTP/1.0 500 Internal Server Error");
// exit;


// 5 minutes execution time
        @set_time_limit(5 * 60);

// Uncomment this one to fake upload time
        usleep(5000);

// Settings
// $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        $targetDir = './Public/many_uploadimg/upload_tmp';
        $uploadDir = './Public/many_uploadimg/upload';

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

// Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }


// Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }

// Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = time().rand(100,999).'.'.pathinfo($_REQUEST["name"],PATHINFO_EXTENSION);
        } elseif (!empty($_FILES)) {
            $fileName = time().rand(100,999).'.'.pathinfo($_FILES["file"]["name"],PATHINFO_EXTENSION);
        } else {
            $fileName = uniqid("file_");
        }

        $md5File = @file('md5list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $md5File = $md5File ? $md5File : array();

        if (isset($_REQUEST["md5"]) && array_search($_REQUEST["md5"], $md5File ) !== FALSE ) {
            die('{"jsonrpc" : "2.0", "result" : null, "id" : "id", "exist": 1}');
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;

// Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;


// Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


// Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
        if ( $done ) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
        }
        $uploadPath=C('MYURL').ltrim($uploadPath,'./');
//        die('{"jsonrpc" : "2.0", "error" : {"code": 1, "message": '.$uploadPath.'}, "id" : "id"}');
        echo json_encode(['code'=>'1001','result'=>$uploadPath]);
    }

    /**
     * @param $code 错误码 1001成功 1002失败
     * @param $result 详细信息
     * @param string $r 为error的时候表示返回错误信息
     * @return bool
     */
    public function ajax($code,$result,$r=''){
        if(empty($r)){
            $this->ajaxReturn(['code'=>$code,'result'=>$result]);
        }else{
            $this->ajaxReturn(['code'=>$code,'result'=>$result]);
            return false;
        }
    }

    public function _empty(){
        $this->redirect('Alerterror/error404');
    }



}